package serverClientDemo;

import java.net.*;
import java.util.Vector;

public class Server {

	public class ClientInfo {
		public InetAddress address;
		public int port;

		public ClientInfo(InetAddress addr, int port) {
			address = addr;
			this.port = port;
		}

		public boolean equals(ClientInfo otherInfo) {
			if (otherInfo.port != this.port)
				return false;
			if (!otherInfo.address.equals(otherInfo.address))
				return false;
			return true;
		}

		@Override
		public String toString() {
			return address.toString() + ':' + port;
		}
	}

	public Vector<ClientInfo> clients;

	public Server() {
		clients = new Vector<ClientInfo>();
	}

	public void run() {
		int port = 49999;
		DatagramSocket socket;
		try {
			socket = new DatagramSocket(port);
			System.out.println("server started, waiting for messages");

			while (true) {
				DatagramPacket request = new DatagramPacket(new byte[1024],
						1024);
				socket.receive(request);

				System.out.println("message received: "
						+ new String(request.getData()));
				InetAddress clientHost = request.getAddress();
				boolean exists = false;

				int clientPort = request.getPort();

				for (ClientInfo client : clients) {
					if (client.equals(new ClientInfo(clientHost, clientPort))) {
						exists = true;
					}
				}
				if (!exists) {
					System.out.println("adding " + clientHost.toString());
					clients.add(new ClientInfo(clientHost, clientPort));
				}

				byte[] buf = request.getData();
				for (ClientInfo client : clients) {
					DatagramPacket reply = new DatagramPacket(buf, buf.length,
							client.address, client.port);
					socket.send(reply);
					System.out.println("reply sent to " + client.toString());
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		Server server = new Server();
		server.run();
	}
}
